package com.sdp.irrigation.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sdp.core.bizc.redis.RedisUtil;
import com.sdp.core.bizc.vo.Result;
import com.sdp.irrigation.cache.EqRealTimeCache;
import com.sdp.irrigation.cache.EqValveCache;
import com.sdp.irrigation.cache.IrrigationCacheKeys;
import com.sdp.irrigation.db.irrigation_eq_real_time.service.IIrrigationEqRealTimeService;
import com.sdp.irrigation.db.irrigation_eq_valve.service.IIrrigationEqValveService;
import com.sdp.irrigation.entity.IrrigationPumpWell;

@RestController
@RequestMapping("/RealTimeController")
public class RealTimeController {
	
	@Autowired
	private RedisUtil redisUtil;
	
	@Autowired 
	private IIrrigationEqRealTimeService iIrrigationEqRealTimeService;
	
	@Autowired
	private IIrrigationEqValveService iIrrigationEqValveService;
	
	@Autowired
	private EqRealTimeCache eqRealTimeCache;
	
	@Autowired
	private EqValveCache eqValveCache;
	
	
	@PostMapping(value = "/queryRealTime")
	public Result<?> getRealTime(@RequestBody IrrigationPumpWell pumpWell) {
		if(StringUtils.isEmpty(pumpWell) || StringUtils.isEmpty(pumpWell.getEqNo())) {
			return Result.error("设备信息不存在");
		}
		
		JSONObject realTime = new JSONObject();
		
		if(!redisUtil.hasKey(IrrigationCacheKeys.getEqRealTimeCacheKey(pumpWell.getEqNo()))) {
			eqRealTimeCache.getEqRealTimeCache(pumpWell.getEqNo());
//			eqRealTimeCache.updateEqRealTimeCache(pumpWell.getEqNo(), iIrrigationEqRealTimeService.queryRealTimeByPwNo(pumpWell.getPwNo()));
		}
		
		if(!redisUtil.hasKey(IrrigationCacheKeys.getValveRealTimeCacheKey(pumpWell.getEqNo()))) {
			
			eqValveCache.updateEqValveCache(pumpWell.getEqNo(), pumpWell.getEqNo(), iIrrigationEqValveService.queryEqValveMapByEqNo(pumpWell.getEqNo()));
		}
		
		realTime.put("eqRealTime", redisUtil.getMap(IrrigationCacheKeys.getEqRealTimeCacheKey(pumpWell.getEqNo())));
		realTime.put("valveRealTime", redisUtil.getMap(IrrigationCacheKeys.getValveRealTimeCacheKey(pumpWell.getEqNo())));

		return Result.ok(realTime);
	}
	
}
